package s2;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import s2.model.Category;
import s2.repo.Repository;

public class CategoryConverter extends StrutsTypeConverter {

	@SuppressWarnings("rawtypes") public Object convertFromString(Map context, String[] values, Class toClass) {
		Long l = convertToLong(values);
		return (l == null) ? null : Repository.getInstance().findCategoryById(l);
	}

	@SuppressWarnings("rawtypes") public String convertToString(Map context, Object o) {
		return ((Category) o).getId().toString();
	}

	private static String getFirstOrNullValue(String[] values) {
		if (values == null || values.length < 1) return null;
		return values[0];
	}

	private static Long convertToLong(String[] values) {
		String s = getFirstOrNullValue(values);
		try {
			return Long.parseLong(s);
		} catch (Exception e) {
			return null;
		}
	}
}
